//
//  AppDelegate.swift
//  LBWeibo
//
//  Created by 李博 on 15/6/23.
//  Copyright © 2015年 libo. All rights reserved.
//

import UIKit
import AFNetworking

///全局变量记录用户登录账号
var sharedUserAccount = UserAccount.loadAccount()

///切换跟控制器的通知
let LBSwitchRootVCNotification = "LBSwitchRootVCNotification"


@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?


    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
        
        // 打印归档保存的用户信息
        print(sharedUserAccount)
        
        setupAppearance()
        
        setupNetwork()
        
        window = UIWindow(frame: UIScreen.mainScreen().bounds);
        window?.backgroundColor = UIColor.whiteColor();
        window?.rootViewController = defaultViewController();
        
        window?.makeKeyAndVisible();
        
        //注册通知
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "switchViewController:", name: LBSwitchRootVCNotification, object: nil)
        
        return true
    }
    ///切换控制器
    func switchViewController(n: NSNotification) {
        
        let isMainVC = n.object as! Bool
        
        window?.rootViewController = isMainVC ? MainViewController() : WelcomeViewController()
    }
    
    ///定义加载的默认控制器
    private func defaultViewController() -> UIViewController {
        
        if sharedUserAccount != nil {
            //如果登陆判断是否有新版本
            return isNewUpdate() ? NewFeatureViewController() : WelcomeViewController()
            
        }
        return MainViewController()
    }
    
    ///是否是新版本
    private func isNewUpdate() -> Bool{
        
        //1.获取应用程序当前版本
        let currVersion = NSBundle.mainBundle().infoDictionary!["CFBundleShortVersionString"] as! String
        let version = NSNumberFormatter().numberFromString(currVersion)!.doubleValue
        //print("当前版本 \(version)")
        
        //2.获取应用程序之前版本，从偏好中读取
        let versionKey = "versionKey"
        let preVersion = NSUserDefaults.standardUserDefaults().doubleForKey(versionKey)
        //print("之前版本 \(preVersion)")
        //3.将当前版本写入偏好设置
        NSUserDefaults.standardUserDefaults().setDouble(version, forKey: versionKey)
        
        //4.返回
        return version > preVersion
    }
    
    ///设置网络
    private func setupNetwork() {
        //设置网络指示器
        AFNetworkActivityIndicatorManager.sharedManager().enabled = true
        //网络缓存
        let urlCache = NSURLCache(memoryCapacity: 4 * 1024 * 1024, diskCapacity: 20 * 1024 * 1024, diskPath: nil)
        NSURLCache.setSharedURLCache(urlCache)
    }
    
    ///设置外观
    private func setupAppearance(){
        
        UINavigationBar.appearance().tintColor = UIColor.orangeColor()
        UITabBar.appearance().tintColor = UIColor.orangeColor()
        
    }
    


}

